const Express = require("express");
const VideoParamServer = require("../../servers/VideoParam");
const ResponseHelper = require("../ResponseHelper");
const router = Express.Router();

router.post("/uploadVideoParam", async (req, res, next) => {
  try {
    const params = req.body;
    console.log("+++++++++++++++++++++++上传的视频参数uploadVideoParam:", params);
    if (!params.scanVideoInfo) {
      return;
    }
    const scanVideoInfo = params.scanVideoInfo;
    let uuid;
    let videoFileName;
    const new_scanVideoInfo = {};
    if (scanVideoInfo.length > 0) {
      scanVideoInfo.forEach((item) => {
        if (item.name == "uuid") {
          uuid = item.value;
        }
        if (item.name == "videoFileName") {
          const videoFileNames = item.value.split("/");
          if (videoFileNames.length > 0) {
            videoFileName = videoFileNames[videoFileNames.length - 3];
            new_scanVideoInfo.newVideoFileName = videoFileName;
          }
        }
        new_scanVideoInfo[item.name] = item.value;
      });
    }
    const videoparams = await VideoParamServer.getVideoParamById(videoFileName);
    console.log("+++++++++++++++++++++++查询的视频参数", videoparams);
    let new_videoparams;
    if (videoparams) {
      new_videoparams = JSON.parse(videoparams.params);
      new_videoparams.push(new_scanVideoInfo);
      const updateVideoParam = JSON.stringify(new_videoparams);
      const updateVideoRes = await VideoParamServer.updateVideoParam(
        videoFileName,
        { params: updateVideoParam }
      );
      console.log("+++++++++++++++++++++++视频参数更新结果", updateVideoRes);
      ResponseHelper.sendData("上传成功!", res);
    } else {
      new_videoparams = [];
      new_videoparams.push(new_scanVideoInfo);
      const addVideoParam = JSON.stringify(new_videoparams);
      const addVideoRes = await VideoParamServer.addVideoParam2({
        id: videoFileName,
        params: addVideoParam,
      });
      console.log("+++++++++++++++++++++++视频参数新增结果", addVideoRes);
      ResponseHelper.sendData("上传成功!", res);
    }
  } catch (err) {
    console.log("+++++++++++++++++++++++err", err);
    ResponseHelper.sendErr(err, res);
  }
});

/**
 * 根据id获取视频参数
 */
router.get("/getVideoParamById/:id", async (req, res) => {
  try {
    const Id = req.params.id;
    const result = await VideoParamServer.getVideoParamById(Id);
    ResponseHelper.sendData(result, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});

module.exports = router;
